package com.yiboshi.rehrs.util.js;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import javax.crypto.Cipher;

public class CipherFactory extends BasePooledObjectFactory<Cipher> {

    private final String transformation;

    public CipherFactory(String transformation) {
        this.transformation = transformation;
    }

    @Override
    public Cipher create() throws Exception {
        return Cipher.getInstance(transformation);
    }

    @Override
    public PooledObject<Cipher> wrap(Cipher cipher) {
        return new DefaultPooledObject<>(cipher);
    }

    @Override
    public void destroyObject(PooledObject<Cipher> p) throws Exception {
        // Cipher 没有显式的销毁方法，直接关闭即可
        super.destroyObject(p);
    }

    @Override
    public boolean validateObject(PooledObject<Cipher> p) {
        // 可选：验证 Cipher 是否处于可用状态
        return p.getObject().getProvider() != null;
    }
}
